#include "evdeploy/algo/person_det.h"
#include "evdeploy/utils/report/tool_report.h"
#include <fstream>
#include <numeric>
#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc.hpp>
#include <sstream>
#include <thread>

namespace ev
{
    namespace algo
    {

        std::mutex PersonDet::m_mutex;
        PersonDet::PersonDet(std::string engine, std::string uuid)
        {
            m_engine = engine;
            m_uuid = uuid;
            EVLOG(INFO) << "use engine:" << m_engine << " and uuid:" << m_uuid;

            ToolReport report;
            // report info
            int code = report.report(2, "ev_base_model", "V1.0.0", "person detection");
            if (code == 0)
            {
                EVLOG(INFO) << "report done successully";
            }
        }

        PersonDet::~PersonDet() {}

        EVStatus PersonDet::Run(cv::Mat &input_mat, std::vector<ev::vision::BoxInfo> &plates_bbox, float thresh)
        {
            REC_TIME(t0);
            cv::Mat cv_in_mat1;
            m_preprocessor.Run(input_mat, cv_in_mat1, 640);

            EVModelData in;
            EVModelData out;
            EVMatData in_mat;
            in.desc = NULL;
            in.mat = &in_mat;
            in.mat_num = 1;
            in_mat.data = cv_in_mat1.data;
            in_mat.data_size = cv_in_mat1.cols * cv_in_mat1.rows * 3 * 4;
            in_mat.width = cv_in_mat1.cols;
            in_mat.height = cv_in_mat1.rows;
            in_mat.aligned_width = cv_in_mat1.cols;
            in_mat.aligned_height = cv_in_mat1.rows;
            in_mat.channel = 3;
            in_mat.type = EV_UINT8;
            std::lock_guard<std::mutex> lock_guard(m_mutex);
            EVDeploy::GetModel().RunInfer(m_uuid, &in, &out);
            float scale = m_preprocessor.GetScale();
            m_postprocessor.Run(out.mat, plates_bbox, scale, thresh, 640, input_mat.cols, input_mat.rows);

            // 注意释放out.mat,否则会有内存泄露!!!!
            if (out.mat)
            {

                delete[] out.mat;
            }
            REC_TIME(t1);
            EVLOG(INFO) << "person det run time(ms):" << RUN_TIME(t1 - t0);
            return EV_SUCCESS;
        }

    } // namespace algo
} // namespace ev
